package com.bifang.module.file.core.biz.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.vo.application.ApplicationVO;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.file.common.enums.FileClassDictEnum;
import com.bifang.module.file.common.vo.fileAppClass.FileAppClassVO;
import com.bifang.module.file.core.util.FileClearCacheUtil;
import com.bifang.module.file.dao.model.FileAppClass;
import com.bifang.module.file.dao.model.FileClass;
import com.bifang.module.file.dao.service.FileAppClassService;
import com.bifang.module.file.dao.service.FileClassService;
import com.bifang.module.system.core.dao.service.SysApplicationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.convert.Convert;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.bifang.engine.assistant.core.exception.AppException;
import org.springframework.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.module.file.common.vo.fileAppRead.FileAppReadVO;
import com.bifang.module.file.common.vo.fileAppRead.FileAppReadKeyVO;
import com.bifang.module.file.common.vo.fileAppRead.FileAppReadQueryVO;
import com.bifang.module.file.core.biz.FileAppReadIntegration;
import com.bifang.module.file.dao.service.FileAppReadService;
import com.bifang.module.file.dao.model.FileAppRead;
/**
 * 应用读取文件权限表业务实现类
 *
 * @author xyh
 * @since 2023-03-17
 */
@ApiService(funcCode = "fileAppRead", title = "应用读取文件权限表")
public class FileAppReadIntegrationImpl implements FileAppReadIntegration {

    @Autowired
    public FileAppReadService fileAppReadService;

    @Autowired
    public FileClassService fileClassService;

    @Autowired
    public SysApplicationService sysApplicationService;

    @Autowired
    public DictHelper dictHelper;

    @Autowired
    public FileAppClassService fileAppClassService;
    @Autowired
    private FileClearCacheUtil fileClearCacheUtil;



    @Override
    @OpApi(funcCode = "fileAppRead0001", title = "应用读取文件权限表分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<FileAppReadVO> getList(FileAppReadQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());

        QueryWrapper<FileAppRead> fileAppReadWrapper = new QueryWrapper<>();
        //若分类标题不为空
        List<FileClass> fileClassList = null;
        List<String> ileClassCodeList = null;
        if(vo.getClassTitle()!=null&&!vo.getClassTitle().equals("")){
            QueryWrapper<FileClass> fileClassWrapper = new QueryWrapper<>();
            fileClassWrapper.lambda().like(FileClass::getClassTitle, vo.getClassTitle());
            fileClassList = fileClassService.list(fileClassWrapper);
            if(fileClassList.size()>0){
                ileClassCodeList = fileClassList.stream().map(FileClass::getFileClassCode).collect(Collectors.toList());
                fileAppReadWrapper
                        .lambda()
                        .eq(!ObjectUtils.isEmpty(vo.getFileClassCode()), FileAppRead::getFileClassCode, vo.getFileClassCode())
                        .eq(!ObjectUtils.isEmpty(vo.getAppId()), FileAppRead::getAppId, vo.getAppId())
                        .in(ileClassCodeList!=null,FileAppRead::getFileClassCode,ileClassCodeList)
                        .ge(!ObjectUtils.isEmpty(vo.getExpireTimeStart()), FileAppRead::getExpireTime, vo.getExpireTimeStart())
                        .le(!ObjectUtils.isEmpty(vo.getExpireTimeEnd()), FileAppRead::getExpireTime, vo.getExpireTimeEnd());

            }else{//标题不存在，直接返回空数据
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
        }else{
            fileAppReadWrapper
                    .lambda()
                    .eq(!ObjectUtils.isEmpty(vo.getFileClassCode()), FileAppRead::getFileClassCode, vo.getFileClassCode())
                    .eq(!ObjectUtils.isEmpty(vo.getAppId()), FileAppRead::getAppId, vo.getAppId())
                    .ge(!ObjectUtils.isEmpty(vo.getExpireTimeStart()), FileAppRead::getExpireTime, vo.getExpireTimeStart())
                    .le(!ObjectUtils.isEmpty(vo.getExpireTimeEnd()), FileAppRead::getExpireTime, vo.getExpireTimeEnd());

        }

        fileAppReadWrapper.lambda()
                .eq(!ObjectUtils.isEmpty(vo.getAuthStatus()), FileAppRead::getAuthStatus, vo.getAuthStatus())
                .orderByDesc(FileAppRead::getAppReadId);
        List<FileAppRead> list = fileAppReadService.list(fileAppReadWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<FileAppRead> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<FileAppReadVO> resultList = Convert.toList(FileAppReadVO.class, pageInfo.getList());
        // 转义数据字典值
        for(FileAppReadVO fileAppReadVO:resultList){
            String fileClassCode = fileAppReadVO.getFileClassCode();
            FileClass fileClass = fileClassService.getById(fileClassCode);
            if(!ObjectUtils.isEmpty(fileClass)){
                fileAppReadVO.setClassTitle(fileClass.getClassTitle());
            }
            ApplicationVO applicationVO = sysApplicationService.getByAppId(fileAppReadVO.getAppId());
            if(!ObjectUtils.isEmpty(applicationVO)){
                fileAppReadVO.setAppName(applicationVO.getAppName());
            }

            //过期时间long转String  expireTimeDate
//            if(fileAppReadVO.getExpireTime()!=null){
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                Date date= new Date(fileAppReadVO.getExpireTime());
//                fileAppReadVO.setExpireTimeString(sdf.format(date));
//            }


        }
         dictHelper.valueToName(resultList, Arrays.asList(FileClassDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "fileAppRead0002", title = "应用读取文件权限表根据主键查询详情", funcType = FuncTypeEnum.query)
    public FileAppReadVO getById(FileAppReadKeyVO vo) {
        FileAppRead entity = fileAppReadService.getById(vo.getAppReadId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        FileAppReadVO result = Convert.convert(FileAppReadVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "fileAppRead0003", title = "应用读取文件权限表保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(FileAppReadVO vo) {
        //主键为空为新增校验
        if(vo.getFileClassCode()==null||("").equals(vo.getFileClassCode())){
            throw new AppException("文件分类编号不能为空");
        }
        if(vo.getAppId()==null){
            throw new AppException("应用id不能为空");
        }
        if(vo.getSecrecyLevel()==null||("").equals(vo.getSecrecyLevel())){
            throw new AppException("保密级别不能为空");
        }
        if(vo.getExpireTime()==null){
            throw new AppException("到期时间不能为空");
        }
        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "fileAppRead0004", title = "应用读取文件权限表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "fileAppRead0004",
            operationName = "应用读取文件权限表新增",
            dataType = "appReadId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public FileAppReadVO add(FileAppReadVO vo) {
        //保存前校验
        checkSave(vo);
        //保存数据
        FileAppRead entity = Convert.convert(FileAppRead.class, vo);
        entity.setCreateName(SessionUtil.getUserId());
        entity.setUpdateName(SessionUtil.getUserId());
        fileAppReadService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setAppReadId(entity.getAppReadId());
        fileClearCacheUtil.clearFileRead(entity.getFileClassCode(),entity.getAppId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "fileAppRead0005", title = "应用读取文件权限表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "fileAppRead0005",
            operationName = "应用读取文件权限表修改",
            dataType = "appReadId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public FileAppReadVO edit(FileAppReadVO vo) {
        if (ObjectUtils.isEmpty(vo.getAppReadId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        FileAppRead oldEntity = fileAppReadService.getById(vo.getAppReadId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        FileAppRead entity = Convert.convert(FileAppRead.class, vo);
        entity.setUpdateName(SessionUtil.getUserId());
        entity.setAuditName(SessionUtil.getUserId());
        entity.setAuditTime(new Date());
        fileAppReadService.updateById(entity);
        fileClearCacheUtil.clearFileRead(entity.getFileClassCode(),entity.getAppId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "fileAppRead0006", title = "应用读取文件权限表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "fileAppRead0006",
            operationName = "应用读取文件权限表删除",
            dataType = "appReadId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(FileAppReadKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getAppReadId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        FileAppRead entity = fileAppReadService.getById(vo.getAppReadId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        fileAppReadService.removeById(vo.getAppReadId());
        fileClearCacheUtil.clearFileRead(entity.getFileClassCode(),entity.getAppId());
    }


    @Override
    @OpApi(funcCode = "fileAppRead0007", title = "文件应用分类授权管理分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<FileAppClassVO> getFileAppClassList(FileAppReadQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());

        QueryWrapper<FileAppClass> fileAppReadWrapper = new QueryWrapper<>();
        //若分类标题不为空
        List<FileClass> fileClassList = null;
        List<String> ileClassCodeList = null;
        if(vo.getClassTitle()!=null&&!vo.getClassTitle().equals("")){
            QueryWrapper<FileClass> fileClassWrapper = new QueryWrapper<>();
            fileClassWrapper.lambda().like(FileClass::getClassTitle, vo.getClassTitle());
            fileClassList = fileClassService.list(fileClassWrapper);
            if(fileClassList.size()>0){
                ileClassCodeList = fileClassList.stream().map(FileClass::getFileClassCode).collect(Collectors.toList());
                fileAppReadWrapper
                        .lambda()
                        .eq(!ObjectUtils.isEmpty(vo.getFileClassCode()), FileAppClass::getFileClassCode, vo.getFileClassCode())
                        .eq(!ObjectUtils.isEmpty(vo.getAppId()), FileAppClass::getAppId, vo.getAppId())
                        .in(ileClassCodeList!=null,FileAppClass::getFileClassCode,ileClassCodeList)
                        .ge(!ObjectUtils.isEmpty(vo.getExpireTimeStart()), FileAppClass::getExpireTime, vo.getExpireTimeStart())
                        .le(!ObjectUtils.isEmpty(vo.getExpireTimeEnd()), FileAppClass::getExpireTime, vo.getExpireTimeEnd());

            }else{//标题不存在，直接返回空数据
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
        }else{
            fileAppReadWrapper
                    .lambda()
                    .eq(!ObjectUtils.isEmpty(vo.getFileClassCode()), FileAppClass::getFileClassCode, vo.getFileClassCode())
                    .eq(!ObjectUtils.isEmpty(vo.getAppId()), FileAppClass::getAppId, vo.getAppId())
                    .ge(!ObjectUtils.isEmpty(vo.getExpireTimeStart()), FileAppClass::getExpireTime, vo.getExpireTimeStart())
                    .le(!ObjectUtils.isEmpty(vo.getExpireTimeEnd()), FileAppClass::getExpireTime, vo.getExpireTimeEnd());
        }

        fileAppReadWrapper.lambda()
                .eq(!ObjectUtils.isEmpty(vo.getAuthStatus()), FileAppClass::getAuthStatus, vo.getAuthStatus())
                .orderByDesc(FileAppClass::getAppClassId);
        List<FileAppClass> list = fileAppClassService.list(fileAppReadWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<FileAppClass> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<FileAppClassVO> resultList = Convert.toList(FileAppClassVO.class, pageInfo.getList());
        // 转义数据字典值
        for(FileAppClassVO fileAppClassVO:resultList){
            String fileClassCode = fileAppClassVO.getFileClassCode();
            FileClass fileClass = fileClassService.getById(fileClassCode);
            if(!ObjectUtils.isEmpty(fileClass)){
                fileAppClassVO.setFileClassTitle(fileClass.getClassTitle());
            }
            ApplicationVO applicationVO = sysApplicationService.getByAppId(fileAppClassVO.getAppId());
            if(!ObjectUtils.isEmpty(applicationVO)){
                fileAppClassVO.setAppName(applicationVO.getAppName());
            }

//            //过期时间long转String  expireTimeDate
//            if(fileAppClassVO.getExpireTime()!=null){
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                Date date= new Date(fileAppClassVO.getExpireTime());
//                fileAppClassVO.setExpireTimeString(sdf.format(date));
//            }

        }
        dictHelper.valueToName(resultList, Arrays.asList(FileClassDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "fileAppRead0008", title = "应用读取文件权限表批量新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "fileAppRead0004",
            operationName = "应用读取文件权限表批量新增",
            dataType = "appReadId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void addBatch(FileAppReadVO vo) {
        List<FileAppRead> entityList = new ArrayList<FileAppRead>();
        for(String fileClassCode : vo.getFileClassCodeList()){
            vo.setFileClassCode(fileClassCode);
            //保存前校验
            checkSave(vo);
            //保存数据
            FileAppRead entity = Convert.convert(FileAppRead.class, vo);

            entityList.add(entity);
        }
        fileAppReadService.saveBatch(entityList);
        for(FileAppRead entity : entityList) {
            fileClearCacheUtil.clearFileRead(entity.getFileClassCode(), entity.getAppId());
        }
    }

}
